//
//  MoreVC.m
//  easyTaxi
//
//  Created by ellenpage on 12-12-7.
//  Copyright (c) 2012年 ellenpage. All rights reserved.
//

#define kIsReadAddress @"isReadAddress"
#define kIsReadSetting @"isReadSetting"
#define kIsReadVantage @"isReadVantage"//积分
#define kIsReadFinance @"isReadFinance"//财务

#define kIsReadActivityAlert @"isReadActivityAlert"//活动声明

#import "MoreVC.h"
#import "SettingVC.h"
#import "AddressBookVC.h"
#import "VantagesVC.h"
#import "Constant.h"
#import "SocketObject.h"
#import "PassValueClass.h"
#import "MBProgressHUD.h"
#import "HelpView.h"
#import "FinanceVC.h"
#import "SysInfoVC.h"
#import "AboutVC.h"
#import <MessageUI/MessageUI.h>
#import "RequestCMD.h"

BOOL userEnable;

@interface MoreVC ()<UITableViewDataSource,UITableViewDelegate,UINavigationControllerDelegate,UITextViewDelegate,MFMessageComposeViewControllerDelegate>

@property (weak, nonatomic) IBOutlet UITableView *customTBView;
@property (retain, nonatomic) NSArray *dataArray;
@property (retain, nonatomic) SettingVC     *settingVC;
@property (retain, nonatomic) AddressBookVC *addressVC;
@property (retain, nonatomic) VantagesVC    *vantageVC;
@property (retain, nonatomic) SysInfoVC     *sysInfoVC;
@property (retain, nonatomic) AboutVC       *aboutVC;
@property (retain, nonatomic) FinanceVC     *fianceVC;

@property (weak, nonatomic)   IBOutlet UIView *feedbackView_Small;
@property (strong, nonatomic) IBOutlet UIView *feedBackView;
@property (weak, nonatomic)   IBOutlet UITextView *feedBackTxtView;
@property (strong, nonatomic) IBOutlet UIView *helpView;
@property (weak, nonatomic) IBOutlet UIWebView *helpWebView;

- (IBAction)hideHelpView;
- (IBAction)summitFeedback:(id)sender;
- (IBAction)cancelFeedback:(id)sender;

@end

@implementation MoreVC

#pragma mark - System Function - 系统函数

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        [self addDataToArray];//加载数据
    }
    return self;
}

- (void)viewDidLoad
{
    _settingVC = [[SettingVC     alloc] init];
    _addressVC = [[AddressBookVC alloc] init];
    _vantageVC = [[VantagesVC    alloc] init];
    _sysInfoVC = [[SysInfoVC     alloc] init];
    _aboutVC   = [[AboutVC       alloc] init];
    _fianceVC  = [[FinanceVC     alloc] init];
    [self  initialData];
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload
{
    [self setCustomTBView:nil];
    [self setFeedBackView:nil];
    [self setFeedBackTxtView:nil];
    [self setFeedbackView_Small:nil];
    [self setHelpView:nil];
    [self setHelpWebView:nil];
    [super viewDidUnload];
}

#pragma mark - InitialData - 初始化数据

- (void)initialData
{
    _feedBackTxtView.delegate = self;
    
    _feedBackView.backgroundColor = [[UIColor darkTextColor] colorWithAlphaComponent:0.65];
    [_feedbackView_Small.layer setCornerRadius:10];
    [_feedbackView_Small.layer setBorderColor:[[UIColor whiteColor] CGColor]];//描边颜色
    [_feedbackView_Small.layer setBorderWidth:2.0];//描边粗细
    [self.view addSubview:_feedBackView];
    _feedBackView.hidden = YES;
    
    [self.view addSubview:self.helpView];
    [self loadWebView];
    self.helpView.hidden = YES;
}

- (void)loadWebView
{
    if (!iP5)
    {
        self.helpWebView.frame = CGRectMake(0, 52, 320, 390);
    }
    else
    {
        self.helpWebView.frame = CGRectMake(0, 52, 320, 448);
    }
    
    NSString *url = @"http://et.ehave.cn/help/PassengerHelp.html";
    [self.helpWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
}

#pragma mark - AddDataToArray - 数据源加入数组中

- (void)addDataToArray
{
    NSArray *array1 = [NSArray arrayWithObjects:@"地址簿",@"积分抽奖",nil];
    NSArray *array2 = [NSArray arrayWithObjects:@"账号设置", nil];
    NSArray *array3 = [NSArray arrayWithObjects:@"分享",@"用户反馈",@"系统消息",@"检查更新",@"打车攻略",@"给产品评分",@"关于", nil];

    _dataArray = [NSArray arrayWithObjects:array1,array2,array3,nil];
}

#pragma mark - TableView DataSource - 数据源

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView//区间数
{
    return [_dataArray count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section//每个区间的个数
{
    int i = 0;
    if (_dataArray.count > 0) {
        NSArray *array = [_dataArray objectAtIndex:section];
        i = array.count;
    }
    return i;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *headStr = nil;
    switch (section)
    {
        case 0:
        {
            headStr = @"系统插件";
            return headStr;
        }
            break;
        case 1:
        {
            headStr = @"设置";
            return headStr;
        }
            break;
        case 2:
        {
            headStr = @"关于";
            return headStr;
        }
            break;
            
        default:
            return headStr;
            break;
    }    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    NSArray *sectionArray = [_dataArray objectAtIndex:indexPath.section];
    NSString *string = [sectionArray objectAtIndex:indexPath.row];
    
    cell.textLabel.text = [NSString stringWithFormat:@"%@",string];
    [cell.textLabel setTextAlignment:UITextAlignmentLeft];
    
    if (indexPath.section == 0)//
    {
        if (indexPath.row == 0)
        {
            bool isReadAddress = [[NSUserDefaults standardUserDefaults] objectForKey:kIsReadAddress];
            if (!isReadAddress)
            {
                cell.detailTextLabel.text = @"New!";
                cell.detailTextLabel.textColor = [UIColor redColor];
            }
        }
        else if(indexPath.row == 1)
        {
            bool isReadVantage = [[NSUserDefaults standardUserDefaults] objectForKey:kIsReadVantage];
            if (!isReadVantage)
            {
                cell.detailTextLabel.text = @"New!";
                cell.detailTextLabel.textColor = [UIColor redColor];
            }
        }
    }
    
    if (indexPath.section == 1)
    {
        if (indexPath.row == 0)
        {

            bool isReadSeeting = [[NSUserDefaults standardUserDefaults] objectForKey:kIsReadSetting];
            if (!isReadSeeting)
            {
                cell.detailTextLabel.text = @"New!";
                cell.detailTextLabel.textColor = [UIColor redColor];
            }
        }
        else if (indexPath.row == 1)
        {
            [YouMengEvent YouMengEvent:@"0019"];//进入财务界面

            bool isReadSeeting = [[NSUserDefaults standardUserDefaults] objectForKey:kIsReadFinance];
            if (!isReadSeeting)
            {
                cell.detailTextLabel.text = @"New!";
                cell.detailTextLabel.textColor = [UIColor redColor];
            }
        }
    }
    if (indexPath.section == 2)
    {
        cell.detailTextLabel.text = nil;
    }
    return cell;
}

#pragma mark - TableView Delegate   - 结构
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    int rowInt     = [indexPath row];
    int sectionInt = [indexPath section];
    switch (sectionInt)
    {
        case 0:
        {
            if (rowInt == 0)
            {
                [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kIsReadAddress];
                [self.navigationController pushViewController:_addressVC animated:YES];
            }
            if (rowInt == 1)
            {
                
                bool isReadOrNot = [[NSUserDefaults standardUserDefaults] objectForKey:kIsReadActivityAlert];
                if (!isReadOrNot)
                {
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"积分活动声明" message:@"本活动是由易打车组织,与苹果公司无关" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
                    [alertView show];
                    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kIsReadActivityAlert];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                }

                [self userLimits];
                
                if (userEnable == YES)
                {
                    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kIsReadVantage];
                    [self.navigationController pushViewController:_vantageVC animated:YES];
                }
            }
        }
            break;
        case 1:
        {
            if (rowInt == 0)
            {
                [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kIsReadSetting];

                [self.navigationController pushViewController:_settingVC animated:YES];
            }
            if (rowInt == 1)
            {
                [self userLimits];

                if (userEnable == YES)
                {
                    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kIsReadFinance];
                    [self.navigationController pushViewController:_fianceVC animated:YES];
                }
            }
        }
            break;
        case 2:
        {
            switch (rowInt)
            {
                case 0:
                {
                    NSString *str1 = @"我正在使用一款很棒的打车应用<易打车>,下载地址是http://t.cn/zYqAdPK";
                    [self sendSMS:str1 recipientList:nil];
                }
                    break;
                case 1:
                {
                    _feedBackView.hidden = NO;
                }
                    break;
                case 2:
                {
                    [self.navigationController pushViewController:_sysInfoVC animated:YES];
                }
                    break;
                case 3://用户更新
                {
                    [self userLimits];
                    
                    if (userEnable == YES)
                    {
                        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kIsFromMoreView];
                        //--------------1005获取公共信息--------------
                        NSString *string    = [RequestCMD requestCMD:kPublicInfo];
                        NSMutableData *data = [RequestCMD getWantedData:string];
                        [[SocketObject sharedInstance].gcdSocket writeData:data withTimeout:-1 tag:kPublicInfo];    
                    }
                }
                    break;
                case 4://使用说明
                {
                    self.helpView.hidden = NO;
                }
                    break;
                case 5:
                {
                    NSString *str = kRateUrl2(520348118);
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
                }
                    break;
                    
                case 6:
                {
                    [self.navigationController pushViewController:_aboutVC animated:YES];
                }
                    break;
                default:
                    break;
            }
        }
            break;

        default:
            break;
    }
}

#pragma mark - Feedback View - 用户反馈界面


- (IBAction)summitFeedback:(id)sender
{
    if ([_feedBackTxtView.text length] == 0)
    {
        UIAlertView *noFeedbackStrAlert = [[UIAlertView alloc] initWithTitle:@"请您输入反馈内容~"
                                                                     message:nil
                                                                    delegate:self
                                                           cancelButtonTitle:@"知道了"
                                                           otherButtonTitles:nil, nil];
        [noFeedbackStrAlert show];
    }
    else
    {
        [PassValueClass sharedIntance].feedbackStr = _feedBackTxtView.text;
        NSString *string1011 = [RequestCMD requestCMD:kUserFeedback];//1023---用户反馈
        NSMutableData *dataToSend1011 = [RequestCMD getWantedData:string1011];
        [[SocketObject sharedInstance].gcdSocket writeData:dataToSend1011 withTimeout:-1 tag:kUserFeedback];
        
        
        MBProgressHUD *HD = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:HD];
        HD.labelText = @"已经提交,感谢你的支持!";
        [HD showAnimated:YES whileExecutingBlock:^{
            //对话框显示时需要执行的操作
            sleep(1);
        } completionBlock:^{[HD removeFromSuperview];}];
        
        [_feedBackTxtView resignFirstResponder];
        _feedBackView.hidden = YES;
    }
}

- (IBAction)cancelFeedback:(id)sender
{
    [_feedbackView_Small setFrame:CGRectMake(22, 29, 276, 260)];
    [_feedBackTxtView resignFirstResponder];
    _feedBackView.hidden = YES;
}

#pragma mark - TextField Delegate - TextField 代理

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"])
    {
        [_feedBackTxtView resignFirstResponder];
        [_feedbackView_Small setFrame:CGRectMake(22, 29, 276, 260)];
        return NO;
    }
    return YES;
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    [_feedbackView_Small setFrame:CGRectMake(22, -10, 276, 260)];
}


#pragma mark - 用户权限管理

- (void)userLimits
{
    if (isTiYanMoShiOk)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"当前处在体验模式" message:@"体验模式下仅能查看信息" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
        [alert show];
        userEnable = NO;
        return;
    }

    if (!isSokectOk)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"服务器未连接,请稍后重试"
                                                        message:nil
                                                       delegate:self
                                              cancelButtonTitle:@"好的"
                                              otherButtonTitles:nil, nil];
        [alert show];
        userEnable = NO;
        return;
    }
    
    if (!isAvaliableCityOk)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"你所在的区域不支持我们的服务,敬请期待~"
                                                        message:nil
                                                       delegate:self
                                              cancelButtonTitle:@"好的"
                                              otherButtonTitles:nil, nil];
        [alert show];
        userEnable = NO;
        return;
    }
    
    if (!isLoginOk)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络问题导致登录异常,请稍后重试"
                                                        message:nil
                                                       delegate:self
                                              cancelButtonTitle:@"好的"
                                              otherButtonTitles:nil, nil];
        [alert show];
        userEnable = NO;
        return;
    }
    
    //3.判断是否已经绑定手机号
    NSString *isBindedStr = [PassValueClass sharedIntance].isBindedStr;
    if (isBindedStr == nil)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"正在获取个人信息请稍后..."
                                                        message:nil
                                                       delegate:self
                                              cancelButtonTitle:@"好的"
                                              otherButtonTitles:nil, nil];
        [alert show];
        userEnable = NO;
        return;
        
    }
    
    if ([isBindedStr isEqualToString:@"0"])
    {
        if (!kIsIphone)
        {
            UIAlertView *signUpAlertView = [[UIAlertView alloc] initWithTitle:@"检测到您的设备不具备短信和运营商电话功能,请使用iPhone体验本程序~"
                                                                      message:nil
                                                                     delegate:self
                                                            cancelButtonTitle:@"知道了"
                                                            otherButtonTitles:nil, nil];
            
            [signUpAlertView show];
            userEnable = NO;
            return;
        }
        else
        {
            UIAlertView *signUpAlertView = [[UIAlertView alloc] initWithTitle:@"手机注册"
                                                                      message:@"为了您的交易安全,请发送一条短信,完成注册"
                                                                     delegate:self
                                                            cancelButtonTitle:@"稍后再试"
                                                            otherButtonTitles:@"发送短信", nil];
            signUpAlertView.tag = kUserLogInAlert;
            [signUpAlertView show];
            userEnable = NO;
            return;
        }
    }
    userEnable = YES;
}

#pragma mark - UIAlertView - alertview代理

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    int i = alertView.tag;
    switch (i)
    {
        case kUserLogInAlert:
        {
            if (buttonIndex == 1)
            {
                NSString *str1 = [GetPhoneInfo getCurrentTimeStamp];
                NSString *str2 = [GetPhoneInfo getCurrentIMSI];
                NSString *contentStr = [NSString stringWithFormat:@"CODE=ETAXI,TYPE=PASSENGER,TIMESTAMPS=%@,IMSI=%@",str1,str2];
                
                NSString *teleNoStr = nil;
                if ([PassValueClass sharedIntance].messageGatewayNoStr != nil)
                {
                    teleNoStr = [PassValueClass sharedIntance].messageGatewayNoStr;
                }
                else
                {
                    teleNoStr = kSignUpNo;
                }
                NSArray *arrry = [NSArray arrayWithObject:teleNoStr];
                
                [self sendSMS:contentStr recipientList:arrry];
                
                MBProgressHUD *HD = [[MBProgressHUD alloc] initWithView:self.view];
                [self.view addSubview:HD];
                HD.labelText = @"正在注册,请耐心等待!";
                [HD showAnimated:YES whileExecutingBlock:^{
                    //对话框显示时需要执行的操作
                    sleep(10);
                } completionBlock:^{[HD removeFromSuperview];}];
            }
        }
            break;
        default:
            break;
    }
}

#pragma mark - 发送短信

- (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSArray *)recipients
{
    MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
    if([MFMessageComposeViewController canSendText])
    {
        controller.body = bodyOfMessage;
        controller.recipients = recipients;
        controller.messageComposeDelegate = self;
        [self presentModalViewController:controller animated:YES];
    }   
}

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    [self dismissModalViewControllerAnimated:YES];
    
    if (result == MessageComposeResultCancelled)
    {
        NSLog(@"Message cancelled");
    }
    else if (result == MessageComposeResultSent)
    {
        NSLog(@"Message sent");
    }
    else
    {
        NSLog(@"Message failed");
    }
}


#pragma mark - 帮助界面

- (IBAction)hideHelpView
{
    self.helpView.hidden = YES;
}

@end
